//#################################################
// 版权所有：鸽子游戏俱乐部
// 系统名称：鸽子游戏俱乐部-移动版
// 文件名称：loginAction.js
// 创建时间：2016年06月29日
// 创建人员：Panda
// 功能说明：login with username and password action
//#################################################

'use strict';

import * as types from './types';

import CommonFunc from '../common/commonFunc';

import * as LoginService from '../services/loginService';

function loginWithUsernamePassword(username, password) {
    return dispatch => {
        //字段校验
        let validateResult = validate(username, password);
        if ( !validateResult.result ) {
            dispatch(validateFailed());
        }
        else {
            //准备开始登陆流程
            // dispatch(loginStart());

            //服务调用
            LoginService.logon(username, password)
            .then((responseData) => {
                if(responseData.code=='200'){
                    dispatch(loginSuccess(responseData.data));
                }
            },
            (responseData) => {
                if (responseData.code!='200') {
                    dispatch(loginFailed(responseData.info, responseData.code));
                }
            })
            .catch((error) => {
                dispatch(loginFailed(error));
            });
        }
    };
}

function validate(username, password) {
    if (CommonFunc.isEmpty(username)) {
        return {
            result: false,
        };
    }

    if (CommonFunc.isEmpty(password)) {
        return {
            result: false,
        };
    }

    return {
        result: true,
        msg: '',
    };
}

function validateFailed() {
    return {
        type: types.LOGIN_LOGINWITHUSERNAMEPASSWORD_VALIDATE_FAILED,
    };
}

function loginSuccess(responseData) {
    return {
        type: types.LOGIN_LOGINWITHUSERNAMEPASSWORD_LOGIN_SUCCESS,
        data: responseData,
    };
}

function loginFailed(error, code = 0) {
    return {
        type: types.LOGIN_LOGINWITHUSERNAMEPASSWORD_LOGIN_FALIED,
        msg: error,
        code: code,
    };
}

function loginStart() {
    return {
        type: types.LOGIN_LOGINWITHUSERNAMEPASSWORD_LOGIN_START,
    };
}

function changeLoginAuth({username, password}) {
    return {
        type: types.LOGIN_LOGINWITHUSERNAMEPASSWORD_CHANGE_LOGIN_AUTH,
        username: username,
        password: password,
    };
}

function clearPassword() {
    return {
        type: types.LOGIN_LOGINWITHUSERNAMEPASSWORD_CLEAR_PASSWORD,
    };
}

function clearLogin() {
    return {
        type: types.LOGIN_LOGINWITHUSERNAMEPASSWORD_CLEAR,
    };
}

function clearLoginFailedMsg() {
    return {
        type: types.LOGIN_CLEAR_LOGIN_FAILED_MSG,
    };
}

module.exports = {
    loginWithUsernamePassword,
    clearLogin,
    clearLoginFailedMsg,
    // changeLoginAuth,
    // clearPassword,
};